package com.eic.framework.core.security;

import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class SecurityMatchers {
    private static final List<String> exts=new ArrayList<>();
    private static final List<String> patterns=new ArrayList<>();
    private static String logout="/logout";
    private static AntPathMatcher matcher = new AntPathMatcher();
    public static void setLogoutUrl(String url){
        logout=url;
    }
    /**
     * 添加不校验文件后缀名,如jpg、js
     * @param exts
     */
    public static void addPermitExtens(String ...exts){
        for(String ext:exts){
            if(ext.startsWith(".")){
                SecurityMatchers.exts.add(ext.toLowerCase());
            }else{
                SecurityMatchers.exts.add("."+ext.toLowerCase());
            }
        }
    }

    /**
     * 添加不校验文件模式,如/druid/**
     * @param patterns
     */
    public static void addPermitPatterns(String ...patterns){
        for(String p:patterns){
            SecurityMatchers.patterns.add(p.toLowerCase());
        }
    }

    public static boolean matchLogout(HttpServletRequest req){
        String url = req.getServletPath();
        if(matcher.match(logout, url)){
            return true;
        }
        return false;
    }

    public static boolean match(HttpServletRequest req){
        String url = req.getServletPath().toLowerCase();
        String method = req.getMethod();
        if(exts.size()>0 && method.equalsIgnoreCase("GET")){
            for(String ext:exts){
                if(url.endsWith(ext)){
                    return true;
                }
            }
        }
        for(String pattern:patterns){
            if(matcher.match(pattern, url)){
                return true;
            }
        }
        return false;
    }
}
